/**
 * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jse.tpl;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;

/**
 * ByteWriter
 */
public class ByteWriter extends Writer {
	
	OutputStream out;
	private final static CharsetEncoder encoder=StandardCharsets.UTF_8.newEncoder();
	
	char[] chars;
	byte[] bytes;
	
	boolean inUse;	// 支持 reentrant
	
	public ByteWriter(int bufferSize) {
		this.chars = new char[bufferSize];
		this.bytes = new byte[bufferSize * ((int)encoder.maxBytesPerChar())];
	}
	
	public ByteWriter init(OutputStream outputStream) {
		inUse = true;
		this.out = outputStream;
		return this;
	}
	
	public void close() {
		inUse = false;
		out = null;
	}
	
	public boolean isInUse() {
		return inUse;
	}
	
	public void flush() throws IOException {
		out.flush();
	}
	
	public void write(String str, int offset, int len) throws IOException {
		int size, byteLen;
		while (len > 0) {
			size = (len > chars.length ? chars.length : len);
			
			str.getChars(offset, offset + size, chars, 0);
			byteLen = Util.encode(encoder,chars, 0, size, bytes);
			out.write(bytes, 0, byteLen);
			
			offset += size;
			len -= size;
		}
	}
	
	public void write(String str) throws IOException {
		write(str, 0, str.length());
	}
	
	public void write(StringBuilder stringBuilder, int offset, int len) throws IOException {
		int size, byteLen;
		while (len > 0) {
			size = (len > chars.length ? chars.length : len);
			
			stringBuilder.getChars(offset, offset + size, chars, 0);
			byteLen = Util.encode(encoder,chars, 0, size, bytes);
			out.write(bytes, 0, byteLen);
			
			offset += size;
			len -= size;
		}
	}
	
	public void write(StringBuilder stringBuilder) throws IOException {
		write(stringBuilder, 0, stringBuilder.length());
	}
	
	public void write(Text text) throws IOException {
		byte[] data = text.getBytes();
		out.write(data, 0, data.length);
	}
	
	public void write(int i) throws IOException {
		if (i == Integer.MIN_VALUE) {
        	out.write(Util.minIntValueBytes, 0, Util.minIntValueBytes.length);
        	return ;
        }
        
        int size = (i < 0) ? Util.stringSize(-i) + 1 : Util.stringSize(i);
        Util.getChars(i, size, chars);
        
        // int len = Utf8Encoder.me.encode(chars, 0, size, bytes);
        // byteWriter.out.write(bytes, 0, len);
        
        for (int j=0; j<size; j++) {
        	bytes[j] = (byte)chars[j];
        }
        out.write(bytes, 0, size);
	}
	
	
	public void write(long value) throws IOException {
		if (value == Long.MIN_VALUE) {
			out.write(Util.minLongValueBytes, 0, Util.minLongValueBytes.length);
            return ;
		}
		
        int size = (value < 0) ? Util.stringSize(-value) + 1 : Util.stringSize(value);
        Util.getChars(value, size, chars);
        
        for (int j=0; j<size; j++) {
        	bytes[j] = (byte)chars[j];
        }
        out.write(bytes, 0, size);
	}
	
	public void write(double doubleValue) throws IOException {
		FloatingDecimal fd = new FloatingDecimal(doubleValue);
		int len = fd.getChars(chars);
		for (int i=0; i<len; i++) {
			bytes[i] = (byte)chars[i];
		}
		out.write(bytes, 0, len);
	}
	
	public void write(float floatValue) throws IOException {
		FloatingDecimal fd = new FloatingDecimal(floatValue);
		int len = fd.getChars(chars);
		for (int i=0; i<len; i++) {
			bytes[i] = (byte)chars[i];
		}
		out.write(bytes, 0, len);
	}
	
	private static final byte[] TRUE_BYTES = "true".getBytes();
	private static final byte[] FALSE_BYTES = "false".getBytes();
	
	public void write(boolean booleanValue) throws IOException {
		out.write(booleanValue ? TRUE_BYTES : FALSE_BYTES);
	}
	
}



